import socket from './socket'
import Store from '../store'
import Vue from 'vue'

    socket.doOpen()
    socket.on('message', onMessage);


// 商品对象
const $symbol = Store.state;

let onceSymbol = null;
let tabIndex = [];
export let Socket = socket;
//计算最终持仓数据
export let maxCcDataList = () => {
        let data = $symbol.ccDataList ? JSON.parse(JSON.stringify($symbol.ccDataList)) : '',
            pcProfitAndLoss = 0,
            _user = $symbol.user;

        if (!_user) return false;
        for (var i = 0; i < data.length; i++) {
            let iItem = data[i],
                typeVal = false, //计价类型
                isBol = false; //是否找到对应的产品
            if (
                iItem.contract.profit_coin != "USD" &&
                iItem.contract.base_coin != "USD"
            ) {
                typeVal = iItem.contract.profit_coin;
            }

            for (var j = 0; j < $symbol.symbolList.length; j++) {
                let jItem = $symbol.symbolList[j];
                for (var z = 0; z < jItem.goods_list.length; z++) {
                    let zItem = jItem.goods_list[z];
                    if (iItem.goods_id == zItem.id) {
                        iItem.zfType = zItem.inAndOut.zfType;
                        let priceSpread = 0, //差价
                            profitAndLoss = 0; //盈亏
                        if (Number(iItem.buy_type) == 1) {
                            //买涨  卖出价 -  订单价
                            iItem.io_price = zItem.inAndOut.out_price;
                            priceSpread = iItem.io_price - iItem.price;
                        } else {
                            //买跌   现价 -  买入价
                            iItem.io_price = zItem.inAndOut.in_price;
                            priceSpread = iItem.price - iItem.io_price;
                        }
                        //计算盈亏
                        if (iItem.type_id != 1 || iItem.contract.profit_coin == "USD") {
                            //已usd为计价货币 或者产品类型不属于外汇
                            //盈亏等于 差价*合约单位*点差
                            profitAndLoss =
                                priceSpread * iItem.contract.unit * Number(iItem.num);
                        } else if (iItem.contract.base_coin == "USD") {
                            //已usd为基础货币
                            //盈亏等于 （差价*合约单位*点差） /  (买涨或买跌的价格)
                            profitAndLoss =
                                (priceSpread * iItem.contract.unit * Number(iItem.num)) /
                                iItem.io_price;
                        } else {
                            //不包括usd切产品类型属于外汇
                            //如果基础货币与计价货币一致 * 最新价 否则 / 最新价
                            var usdHL = getUSDExchangeRate(iItem.contract.profit_coin);
                            profitAndLoss =
                                priceSpread * iItem.contract.unit * Number(iItem.num);
                            switch (usdHL.countType) {
                                case 1:
                                    profitAndLoss *= usdHL.newPrice;
                                    break;
                                case 2:
                                    profitAndLoss /= usdHL.newPrice;
                                    break;
                            }
                        }
                        profitAndLoss += Number(iItem.interest);
                        pcProfitAndLoss += Number(profitAndLoss);
                        profitAndLoss = profitAndLoss.toFixed(2);
                        iItem.yingkui = profitAndLoss; //盈亏赋值
                        iItem.inAndOut.in_price = zItem.inAndOut.in_price; //买入价
                        iItem.inAndOut.out_price = zItem.inAndOut.out_price; //卖出价
                        isBol = true;

                        break;
                    }
                }
                if (isBol) {
                    break;
                }
            }
        }
        pcProfitAndLoss = Number(pcProfitAndLoss).toFixed(2);
        return {
            data,
            pcProfitAndLoss
        };
    }
    //获取对应汇率
function getUSDExchangeRate(profit_coin) {
    let isBol = false,
        countType = 0,
        newPrice = 0;

    for (var j = 0; j < $symbol.symbolList.length; j++) {
        let jItem = $symbol.symbolList[j];
        for (var z = 0; z < jItem.goods_list.length; z++) {
            let zItem = jItem.goods_list[z];
            if (
                (profit_coin == zItem.base_coin && zItem.profit_coin == 'USD') ||
                (profit_coin == zItem.profit_coin && zItem.base_coin == 'USD')
            ) {
                newPrice = Number(zItem.new_price);
                countType = profit_coin == zItem.base_coin ? 1 : 2; //1 为* 2为/
                if (countType == 2 && newPrice == 0) {
                    countType = 0;
                }
                isBol = true;
                break;
            }
        }
        if (isBol) {
            break;
        }
    }
    return {
        newPrice,
        countType
    };
}
//挂单最终数据
export let maxGdDataList = () => {
    let _data = $symbol.gdDataList ? JSON.parse(JSON.stringify($symbol.gdDataList)) : '';
    var _lists = $symbol.symbolList,
        _user = $symbol.user;
    if (!_user) return false;
    if (_lists && _lists.length) {
        for (var i = 0; i < _data.length; i++) {
            let iItem = _data[i];
            for (var j = 0; j < _lists.length; j++) {
                let jItem = _lists[j];
                for (var z = 0; z < jItem.goods_list.length; z++) {
                    let zItem = jItem.goods_list[z];
                    if (iItem.goods_id == zItem.id) {
                        iItem.zfType = zItem.inAndOut.zfType;
                        if (Number(iItem.buy_type) == 1)
                        //买涨
                            iItem.new_price = zItem.inAndOut.in_price;
                        else {
                            //买跌
                            iItem.new_price = zItem.inAndOut.out_price;
                        }
                    }
                }
            }
        }
    }
    return _data;
}

//数据搜索
export const dataSearch = (_searchDataVal, _item) => {
    var _bol = false;
    if ((_searchDataVal.goods_type == _item.type_id || _searchDataVal.goods_type == 0 || _searchDataVal.goods_type == "") && (_searchDataVal.hold_type == _item.buy_type || _searchDataVal.hold_type == 0 || _searchDataVal.hold_type == "")) {
        if (_searchDataVal.time_start && _searchDataVal.time_end) {
            var _minTime = new Date(_searchDataVal.time_start).getTime();
            var _maxTime = new Date(_searchDataVal.time_end).getTime();
            var _dataTime = _item.create_time * 1000;
            if (_minTime <= _dataTime && _maxTime >= _dataTime) {
                _bol = true;
            }
        } else {
            _bol = true;
        }
    }
    return _bol;
}
//个人资产信息
export const userAssetNews=()=>{
    let _user = $symbol.user,
        _maxCcDataList=maxCcDataList(),
        sumUpAsset = 0,
        bond = 0,
        usable = 0,
        netValue = 0,
        marginLevel = "--",
        forcedClosings = "--"; //用户信息
      if (_user) {
        var maxPrice =_maxCcDataList? Number(_maxCcDataList.pcProfitAndLoss):0; //总盈亏
        sumUpAsset = Number(_user.money); //总资产
        bond = Number(_user.bond).toFixed(2); //占用保证金
        usable = (sumUpAsset - bond + maxPrice).toFixed(2); //可用 总资产-保证金 +总盈亏
        netValue = (sumUpAsset + maxPrice).toFixed(2); //净值   总资产+总盈亏
        if (bond != 0) {
          forcedClosings = (bond * 0.2).toFixed(2); //强制平仓点  保证金 *0.2
          marginLevel =
            (((sumUpAsset + maxPrice) / bond) * 100).toFixed(2) + "%"; //按金水平 (总资产+总盈亏)/保证金
        }
      }
      usable=usable<=0?'0.00':usable;
      sumUpAsset = Number(sumUpAsset).toFixed(2);
      return {
        sumUpAsset,
        bond,
        usable,
        netValue,
        marginLevel,
        forcedClosings
      };
}
export const fireKeyEvent = (el,  evtType,  keyCode) => {
    var  doc  =  el.ownerDocument,
        win  =  doc.defaultView  ||  doc.parentWindow,
        evtObj;
    if (doc.createEvent) {
        if (win.KeyEvent)  {
            evtObj  =  doc.createEvent('KeyEvents');
            evtObj.initKeyEvent( evtType,  true,  true,  win,  false,  false,  false,  false,  keyCode,  0 );
        } else  {
            evtObj  =  doc.createEvent('UIEvents');
            Object.defineProperty(evtObj,  'keyCode',   {         get :   function()  {  return  this.keyCodeVal;  }     });         
            Object.defineProperty(evtObj,  'which',   {         get :   function()  {  return  this.keyCodeVal;  }     });
            evtObj.initUIEvent( evtType,  true,  true,  win,  1 );
            evtObj.keyCodeVal  =  keyCode;
            if  (evtObj.keyCode  !==  keyCode)  {         console.log("keyCode "  +  evtObj.keyCode  +  " 和 ("  +  evtObj.which  +  ") 不匹配");     }
        }
        el.dispatchEvent(evtObj);
    } 
    else  if (doc.createEventObject) {
        evtObj  =  doc.createEventObject();
        evtObj.keyCode  =  keyCode;
        el.fireEvent('on'  +  evtType,  evtObj);
    }
}


function onMessage(data) {
    // symbol请求完成数据时
    if ($symbol.symbolObj && onceSymbol && $symbol['symbolObj']['商品']) {
        //商品类型索引、
        for (const iterator of $symbol.symbolList) {
            tabIndex.push(iterator.type_name)
        }
        onceSymbol = !1
    }
    // K线历史数据
    if (data == null || data.type == 'kline') return;
    // 
    else if (data.type == 'new') {
        var date = JSON.parse(data.date);
        Store.commit('setBlastingWarehouse', date.type);
    } else {

        // 遍历更改商品最新价格...
        if (data.type == "market") {
            //symbol已有数据，类型已有数据。
            if ($symbol.symbolObj && $symbol['symbolObj']['商品'] && tabIndex.length) {
                //遍历商品类型
                for (let i = 0; i < tabIndex.length; i++) {
                    //遍历商品类型列表
                    for (let j = 0; j < $symbol['symbolObj'][tabIndex[i]].goods_list.length; j++) {
                        //symbol的code与最新数据的code一致时
                        if (data.date[$symbol['symbolObj'][tabIndex[i]].goods_list[j].system_code] != null) {

                            //涨幅类型 0不变  2跌  1涨
                            let zfType = data.date[$symbol['symbolObj'][tabIndex[i]].goods_list[j].system_code].real - $symbol['symbolObj'][tabIndex[i]].goods_list[j].inAndOut.new_price;
                            if (zfType > 0) {
                                zfType = 1;
                            } else if (zfType < 0) {
                                zfType = 2;
                            } else {
                                zfType = $symbol['symbolObj'][tabIndex[i]].goods_list[j].inAndOut.zfType;
                            }

                            //涨幅
                            $symbol['symbolObj'][tabIndex[i]].goods_list[j].inAndOut.zfType = zfType
                                //最新价
                            $symbol['symbolObj'][tabIndex[i]].goods_list[j].inAndOut.new_price = data.date[$symbol['symbolObj'][tabIndex[i]].goods_list[j].system_code].real
                                //卖出价
                            $symbol['symbolObj'][tabIndex[i]].goods_list[j].inAndOut.out_price = data.date[$symbol['symbolObj'][tabIndex[i]].goods_list[j].system_code].sell
                                //买入价
                            $symbol['symbolObj'][tabIndex[i]].goods_list[j].inAndOut.in_price = data.date[$symbol['symbolObj'][tabIndex[i]].goods_list[j].system_code].buy
                                //最新价      
                            $symbol['symbolObj'][tabIndex[i]].goods_list[j].new_price = data.date[$symbol['symbolObj'][tabIndex[i]].goods_list[j].system_code].real
                                //最高价
                            $symbol['symbolObj'][tabIndex[i]].goods_list[j].today_high_price = data.date[$symbol['symbolObj'][tabIndex[i]].goods_list[j].system_code].high
                                //最低价
                            $symbol['symbolObj'][tabIndex[i]].goods_list[j].today_low_price = data.date[$symbol['symbolObj'][tabIndex[i]].goods_list[j].system_code].low
                        }
                    }
                }

            }


        } else {

            // 首次时ws返回所有行情的买入卖出最新价
            onceSymbol = data;
        }






    }
}
//手机号加密
export const phoneMd = (phone) => {
        var mid = phone.substr(0, 3) + '****' + phone.substr(7);
        return mid;
    }
    // 返回完整时间
export const timeToDate = value => {
    let date = new Date(value * 1000);
    return date.getFullYear() + '-' + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ' +
        (date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours()) + ':' + (date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()) + ':' + (date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds());
}

export const toFixed = (num, s) => {
    var changenum = (parseInt(num * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();
    var index = changenum.indexOf(".");
    if (index < 0 && s > 0) {
        changenum = changenum + ".";
        for (var i = 0; i < s; i++) {
            changenum = changenum + "0";
        }

    } else {
        index = changenum.length - index - 1;
        if (index > s) {
            changenum += '';
            changenum = changenum.substring(0, changenum.indexOf(".") + 1 + s);
        } else {
            for (var i = 0; i < (s - index); i++) {
                changenum = changenum + "0";
            }
        }


    }

    return changenum;


}




// export const selectText = (textbox, startIndex, stopIndex) => {
//     if (textbox.createTextRange) {
//         //ie
//         var range = textbox.createTextRange();
//         range.collapse(true);
//         range.moveStart("character", startIndex); //起始光标
//         range.moveEnd("character", stopIndex - startIndex); //结束光标
//         range.select(); //不兼容苹果
//     } else {
//         //firefox/chrome
//         textbox.setSelectionRange(startIndex, stopIndex);
//     }
// }
export const copy = (val) => {
    var _input = document.createElement("input");
    _input.value = val;
    document.body.appendChild(_input);

    _input.style.opacity = 0;
    _input.setAttribute("readonly", "readonly");
    _input.select();
    var demo = new Vue();
    // selectText(_input, 0, val.length);
    if (document.execCommand("copy", false, null)) {
        document.execCommand("copy", false, null); // 执行浏览器复制命令
        demo.$Message.success({
            content: "复制成功",
            duration: 1,

        });
    } else {
        demo.$Message.error({
            content: "不兼容,请手动复制",
            duration: 1,
        });
    }
    _input.remove();
};

const bankList = {
    "SRCB": "深圳农村商业银行",
    "BGB": "广西北部湾银行",
    "SHRCB": "上海农村商业银行",
    "BJBANK": "北京银行",
    "WHCCB": "威海市商业银行",
    "BOZK": "周口银行",
    "KORLABANK": "库尔勒市商业银行",
    "SPABANK": "平安银行",
    "SDEB": "顺德农商银行",
    "HURCB": "湖北省农村信用社",
    "WRCB": "无锡农村商业银行",
    "BOCY": "朝阳银行",
    "CZBANK": "浙商银行",
    "HDBANK": "邯郸银行",
    "BOC": "中国银行",
    "BOD": "东莞银行",
    "CCB": "中国建设银行",
    "ZYCBANK": "遵义市商业银行",
    "SXCB": "绍兴银行",
    "GZRCU": "贵州省农村信用社",
    "ZJKCCB": "张家口市商业银行",
    "BOJZ": "锦州银行",
    "BOP": "平顶山银行",
    "HKB": "汉口银行",
    "SPDB": "上海浦东发展银行",
    "NXRCU": "宁夏黄河农村商业银行",
    "NYNB": "广东南粤银行",
    "GRCB": "广州农商银行",
    "BOSZ": "苏州银行",
    "HZCB": "杭州银行",
    "HSBK": "衡水银行",
    "HBC": "湖北银行",
    "JXBANK": "嘉兴银行",
    "HRXJB": "华融湘江银行",
    "BODD": "丹东银行",
    "AYCB": "安阳银行",
    "EGBANK": "恒丰银行",
    "CDB": "国家开发银行",
    "TCRCB": "江苏太仓农村商业银行",
    "NJCB": "南京银行",
    "ZZBANK": "郑州银行",
    "DYCB": "德阳商业银行",
    "YBCCB": "宜宾市商业银行",
    "SCRCU": "四川省农村信用",
    "KLB": "昆仑银行",
    "LSBANK": "莱商银行",
    "YDRCB": "尧都农商行",
    "CCQTGB": "重庆三峡银行",
    "FDB": "富滇银行",
    "JSRCU": "江苏省农村信用联合社",
    "JNBANK": "济宁银行",
    "CMB": "招商银行",
    "JINCHB": "晋城银行JCBANK",
    "FXCB": "阜新银行",
    "WHRCB": "武汉农村商业银行",
    "HBYCBANK": "湖北银行宜昌分行",
    "TZCB": "台州银行",
    "TACCB": "泰安市商业银行",
    "XCYH": "许昌银行",
    "CEB": "中国光大银行",
    "NXBANK": "宁夏银行",
    "HSBANK": "徽商银行",
    "JJBANK": "九江银行",
    "NHQS": "农信银清算中心",
    "MTBANK": "浙江民泰商业银行",
    "LANGFB": "廊坊银行",
    "ASCB": "鞍山银行",
    "KSRB": "昆山农村商业银行",
    "YXCCB": "玉溪市商业银行",
    "DLB": "大连银行",
    "DRCBCL": "东莞农村商业银行",
    "GCB": "广州银行",
    "NBBANK": "宁波银行",
    "BOYK": "营口银行",
    "SXRCCU": "陕西信合",
    "GLBANK": "桂林银行",
    "BOQH": "青海银行",
    "CDRCB": "成都农商银行",
    "QDCCB": "青岛银行",
    "HKBEA": "东亚银行",
    "HBHSBANK": "湖北银行黄石分行",
    "WZCB": "温州银行",
    "TRCB": "天津农商银行",
    "QLBANK": "齐鲁银行",
    "GDRCC": "广东省农村信用社联合社",
    "ZJTLCB": "浙江泰隆商业银行",
    "GZB": "赣州银行",
    "GYCB": "贵阳市商业银行",
    "CQBANK": "重庆银行",
    "DAQINGB": "龙江银行",
    "CGNB": "南充市商业银行",
    "SCCB": "三门峡银行",
    "CSRCB": "常熟农村商业银行",
    "SHBANK": "上海银行",
    "JLBANK": "吉林银行",
    "CZRCB": "常州农村信用联社",
    "BANKWF": "潍坊银行",
    "ZRCBANK": "张家港农村商业银行",
    "FJHXBC": "福建海峡银行",
    "ZJNX": "浙江省农村信用社联合社",
    "LZYH": "兰州银行",
    "JSB": "晋商银行",
    "BOHAIB": "渤海银行",
    "CZCB": "浙江稠州商业银行",
    "YQCCB": "阳泉银行",
    "SJBANK": "盛京银行",
    "XABANK": "西安银行",
    "BSB": "包商银行",
    "JSBANK": "江苏银行",
    "FSCB": "抚顺银行",
    "HNRCU": "河南省农村信用",
    "COMM": "交通银行",
    "XTB": "邢台银行",
    "CITIC": "中信银行",
    "HXBANK": "华夏银行",
    "HNRCC": "湖南省农村信用社",
    "DYCCB": "东营市商业银行",
    "ORBANK": "鄂尔多斯银行",
    "BJRCB": "北京农村商业银行",
    "XYBANK": "信阳银行",
    "ZGCCB": "自贡市商业银行",
    "CDCB": "成都银行",
    "HANABANK": "韩亚银行",
    "CMBC": "中国民生银行",
    "LYBANK": "洛阳银行",
    "GDB": "广东发展银行",
    "ZBCB": "齐商银行",
    "CBKF": "开封市商业银行",
    "H3CB": "内蒙古银行",
    "CIB": "兴业银行",
    "CRCBANK": "重庆农村商业银行",
    "SZSBK": "石嘴山银行",
    "DZBANK": "德州银行",
    "SRBANK": "上饶银行",
    "LSCCB": "乐山市商业银行",
    "JXRCU": "江西省农村信用",
    "ICBC": "中国工商银行",
    "JZBANK": "晋中市商业银行",
    "HZCCB": "湖州市商业银行",
    "NHB": "南海农村信用联社",
    "XXBANK": "新乡银行",
    "JRCB": "江苏江阴农村商业银行",
    "YNRCC": "云南省农村信用社",
    "ABC": "中国农业银行",
    "GXRCU": "广西省农村信用",
    "PSBC": "中国邮政储蓄银行",
    "BZMD": "驻马店银行",
    "ARCU": "安徽省农村信用社",
    "GSRCU": "甘肃省农村信用",
    "LYCB": "辽阳市商业银行",
    "JLRCU": "吉林农信",
    "URMQCCB": "乌鲁木齐市商业银行",
    "XLBANK": "中山小榄村镇银行",
    "CSCB": "长沙银行",
    "JHBANK": "金华银行",
    "BHB": "河北银行",
    "NBYZ": "鄞州银行",
    "LSBC": "临商银行",
    "BOCD": "承德银行",
    "SDRCU": "山东农信",
    "NCB": "南昌银行",
    "TCCB": "天津银行",
    "WJRCB": "吴江农商银行",
    "CBBQS": "城市商业银行资金清算中心",
    "HBRCU": "河北省农村信用社"
};

export const getBankName = (val) => {
    return bankList[val];
};

export const ScrollTop = (number = 0, time) => {
    if (!time) {
        document.body.scrollTop = document.documentElement.scrollTop = number;
        return number;
    }
    const spacingTime = 20; // 设置循环的间隔时间  值越小消耗性能越高
    let spacingInex = time / spacingTime; // 计算循环的次数
    let nowTop = document.body.scrollTop + document.documentElement.scrollTop; // 获取当前滚动条位置
    let everTop = (number - nowTop) / spacingInex; // 计算每次滑动的距离
    let scrollTimer = setInterval(() => {
        if (spacingInex > 0) {
            spacingInex--;
            ScrollTop(nowTop += everTop);
        } else {
            clearInterval(scrollTimer); // 清除计时器
        }
    }, spacingTime);
};